package com.jbwz.web.cms.controller;


import com.jbwz.web.cms.entity.SavedFile;
import com.jbwz.web.cms.service.SavedFileService;
import com.jbwz.web.common.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yyh
 * @since 2022-02-03 09:32:08
 */
@Slf4j
@Controller
@RequestMapping("/dfile")
public class FileDownloadController extends BaseController {

    @Autowired
    SavedFileService savedFileService;

    @GetMapping("/img/{id}")
    public void downloadImg(HttpServletResponse response, @PathVariable("id") Long id) {
        SavedFile savedFile = savedFileService.getById(id);
        if (Objects.isNull(savedFile) || !StringUtils.hasLength(savedFile.getFilePath())) {
            log.error("下载图片Id不存在");
        }
        File file = new File(savedFile.getFilePath());
        if (file.exists()) {
            String fileName = savedFile.getOrgName() + "." + savedFile.getFileExt();
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));// 设置文件名
            byte[] buffer = new byte[1024];
            try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) {
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                log.error("下载图片错误", e);
            }
        } else {
            log.error("下载的文件不存在：{}", savedFile.getFilePath());
        }
    }
}
